package org.styx.seata.tcc.order.tcc.impl;

import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.styx.common.utils.ResultHolder;
import org.styx.seata.tcc.order.domain.Order;
import org.styx.seata.tcc.order.mapper.OrderMapper;
import org.styx.seata.tcc.order.tcc.OrderTccAction;

import java.math.BigDecimal;

/**
 * @date 2021/10/8
 * @auther uranus
 */
@Component
@Slf4j
public class OrderTccActionImpl implements OrderTccAction {

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepareCreateOrder(BusinessActionContext businessActionContext,Long id,Long userId, Long productId, Integer count, BigDecimal money) {
        Order order=new Order();
        order.setCount(count);
        order.setUserId(userId);
        order.setProductId(productId);
        order.setMoney(money);
        order.setStatus(0);
        order.setId(id);
        orderMapper.insert(order);
        //order.setId(order.getId());
        log.info("创建订单第一阶段，冻结订单成功!");

        ResultHolder.setResult(OrderTccAction.class, businessActionContext.getXid(),
                "p");
        return true;
    }
    @Transactional
    @Override
    public boolean commit(BusinessActionContext context) {
        log.info("是否执行提交订单");
        System.out.println(ResultHolder.getResult(OrderTccAction.class,
                context.getXid()));
        if(ResultHolder.getResult(OrderTccAction.class,context.getXid())==null){
            return true;
        }
        //修改订单状态0--->1正常状态的改变
        Long orderId=
                Long.parseLong(context.getActionContext("id").toString());
        Order order=new Order();
        order.setStatus(1);
        order.setId(orderId);
        orderMapper.updateById(order);
        log.info("创建订单第二阶段，提交订单，解冻成功");
        //删除标识，防止一直重复提交
        ResultHolder.removeResult(OrderTccAction.class,context.getXid());

        return true;
    }
    @Transactional
    @Override
    public boolean rollback(BusinessActionContext context) {
        //第一阶段没有完成的情况下，不必执行回滚
        //因为第一阶段有本地事务，事务失败时已经进行了回滚。
        //如果这里第一阶段成功，而其他全局事务参与者失败，这里会执行回滚
        //幂等性控制：如果重复执行回滚则直接返回
        log.info("创建Order第二阶段回滚，删除订单 - {}",context.getXid());
        //判断第一阶段的成功标记，没有标记则不执行提交操作
        if(ResultHolder.getResult(OrderTccAction.class,context.getXid())==null){
            return true;
        }
        //通过订单ID
        Long orderId=Long.parseLong(context.getActionContext("id").toString());
        orderMapper.deleteById(orderId);
        log.info("创建订单第二阶段，回滚订单，删除成功");
        //删除标识，防止一直重复提交
        ResultHolder.removeResult(OrderTccAction.class,context.getXid());
        return true;
    }
}
